<?php

class Book extends CActiveRecord {
    /**
     * The followings are the available columns in table 'www_books':
     * @var integer $id
     * @var string $name
     * @var double $words
     * @var integer $edit_format
     * @var integer $published_date
     * @var string $published_unit
     * @var string $summary
     * @var integer $created
     * @var integer $updated
     */

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{books}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
            array('name, author, words, edit_format, published_date, published_unit, summary, order_pos', 'required'),
            array('edit_format, published_date, created, updated, node_id, status, order_pos', 'numerical', 'integerOnly' => true),
            array('is_picking, is_recommend', 'boolean', 'trueValue' => 1, 'falseValue' => 0),
            array('words', 'numerical'),
            array('name, author, published_unit, cover_saved_path', 'length', 'max' => 200),
            array('cover_saved_path', 'file', 'on' => 'insert',
                'allowEmpty' => false,
                'types' => 'jpg, gif',
                'maxSize' => 1024 * 1024 * 10,
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
        return array(
            // 所属栏目
            'node' => array(self::BELONGS_TO, 'Node', 'node_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'Id',
            'node_id' => Yii::t('common', 'node_id'),
            'is_recommend' => Yii::t('common', 'is_recommend'),
            'is_picking' => Yii::t('common', 'is_picking'),
            'name' => Yii::t('book', 'name'),
            'author' => Yii::t('book', 'author'),
            'cover_saved_path' => Yii::t('book', 'cover_saved_path'),
            'words' => Yii::t('book', 'words'),
            'edit_format' => Yii::t('book', 'edit_format'),
            'published_date' => Yii::t('book', 'published_date'),
            'published_unit' => Yii::t('book', 'published_unit'),
            'summary' => Yii::t('book', 'summary'),
            'order_pos' => Yii::t('common', 'order_pos'),
            'status' => Yii::t('options', 'status'),
            'created' => Yii::t('common', 'created'),
            'updated' => Yii::t('common', 'updated'),
        );
    }

    const EDIT_FORMAT_SELF = 1;
    const EDIT_FORMAT_COOPERATION = 2;
    public function getEditFormatOptions () {
        return array(
            self::EDIT_FORMAT_SELF => Yii::t('book', 'edit_format_self'),
            self::EDIT_FORMAT_COOPERATION  => Yii::t('book', 'edit_format_cooperation'),
        );
    }

    // "status" field Icon format
    public function getStatusIconFormat() {
        switch ($this->status) {
            case Options::STATUS_DRAFT:
                $img = 'status_draft.gif';
                break;
            case Options::STATUS_PUBLISHED:
                $img = 'status_published.gif';
                break;
            case Options::STATUS_PENDING_DELETE:
                $img = 'status_pending_delete.gif';
                break;
            default:
                $img = 'status_unknown.gif';
        }
        return CHtml::image(Yii::app()->assetManager->baseUrl . '/backend/images/' . $img);
    }

    // status AJax submit
    public function getStatusAjaxFormat() {
        return CHtml::ajaxLink($this->statusIconFormat,
            Yii::app()->createUrl('backend/books/changeStatus'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#status{$this->id}",
            ),
            array('id' => "status{$this->id}")
        );
    }

    // “是否推荐”图标格式
    public function getIsRecommendIconFormat() {
        $img = (intval($this->is_recommend) == Options::RECOMMEND_YES)
            ? 'yes.gif' : 'no.gif';
        return CHtml::image(Yii::app()->baseUrl . '/assets/backend/images/' . $img);
    }

    // change recommend status ajax link
    public function getIsRecommendAjaxLink() {
        return CHtml::ajaxLink($this->isRecommendIconFormat,
            Yii::app()->createUrl('backend/books/changeRecommend'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#recommend{$this->id}",
            ),
            array('id' => "recommend{$this->id}")
        );
    }

    // “是否精品”图标格式
    public function getIsPickingIconFormat() {
        $img = (intval($this->is_picking) == Options::PICKING_YES)
            ? 'yes.gif' : 'no.gif';
        return CHtml::image(Yii::app()->baseUrl . "/assets/backend/images/{$img}");
    }

    // change picking status ajax link
    public function getIsPickingAjaxLink() {
        return CHtml::ajaxLink($this->isPickingIconFormat,
            Yii::app()->createUrl('/backend/books/changePicking'),
            array(
                'type' => 'POST',
                'data' => 'id=' . $this->id,
                'dataType' => 'text',
                'update' => "#picking{$this->id}",
            ),
            array('id' => "picking{$this->id}")
        );
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'created',
                'updateAttribute' => 'updated',
            )
        );
    }

    public function getUpdatedFormatted() {
        return ($this->updated) ? date('Y-m-d', $this->updated) : '';
    }

    public function getEditFormatTextFormat() {
        return $this->editFormatOptions[$this->edit_format];
    }

    /**
     * get logo picture saved path
     * @return string
     */
    public function getCoverPath() {
        return YHtml::uploadPath('book/') . $this->cover_saved_path;
    }

    public function getCoverSource() {
        return Yii::app()->params['upload_directory']['book'] . $this->cover_saved_path;
    }

    // 设置章节分类所属书籍
    public function addChapterCategory($book_chapter_category) {
        $book_chapter_category->book_id = $this->id;
        return $book_chapter_category->save();
    }

    private $_original_cover_saved_path;
    public function afterFind() {
        $this->_original_cover_saved_path = $this->cover_saved_path;
    }

    protected function beforeSave() {
        parent::beforeSave();
        
        $uploading_file = CUploadedFile::getInstance($this, 'cover_saved_path');
        if (is_object($uploading_file) && get_class($uploading_file) === 'CUploadedFile') {
            if (!$this->isNewRecord) {
                @unlink(Book::model()->findByPk($this->id)->coverPath);
            }
            $filename = md5($this->name . date('Y-m-d H:m:s', time())) . '.' . $uploading_file->getExtensionName();
            $this->cover_saved_path = $filename;
            $uploading_file->saveAs(YHtml::uploadPath('book/') . $filename);
        } else {
            $this->cover_saved_path = $this->_original_cover_saved_path;
        }

        return true;
    }

    // 删除记录的同时删除 logo 文件
    public function afterDelete() {
        @unlink($this->coverPath);
    }
}